package com.motu.monstercity.server.game.verticle;

import com.motu.monstercity.module.common.utility.EventBusConstant;
import com.motu.monstercity.server.game.logic.RankActManager;
import com.motu.monstercity.server.game.timedtask.*;
import com.motu.vertx.module.utility.threadpool.DBLogManager;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.MessageConsumer;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 定时任务工作线程（多进程多线程，用于执行具体的定时任务逻辑）
 */
public class WorkVerticle extends AbstractVerticle {

	public static final Logger logger = LoggerFactory.getLogger(WorkVerticle.class);

	@Override
	public void start(Promise<Void> future) {
		EventBus eb = vertx.eventBus();
		String address = EventBusConstant.getAddress(EventBusConstant.TIME_WORK);

		MessageConsumer<JsonObject> consumer = eb.consumer(address);
		consumer.handler(message -> {
			try {
				JsonObject receiveInfo = message.body();
				logger.info("###receiveInfo = " + receiveInfo.toString());
				int cmd = receiveInfo.getInteger("cmd");// 接收命令
				JsonObject data = receiveInfo.getJsonObject("data");// 接收JsonObject数据
				switch (cmd) {
					case TimeTaskCmd.WORK_GAME_TIME_TASK:// 执行GameTimeTask定时任务
						GameTimeTask.runGameTimeTask(data);
						break;
					case TimeTaskCmd.WORK_ACT_CLOSE:// 执行活动结算定时任务
						ActCloseTask.runTask(data);
						break;
					case TimeTaskCmd.WORK_ACT_END:// 执行活动结束定时任务
						ActEndTask.runTask(data);
						break;
					case TimeTaskCmd.WORK_SERVER_FEAST:// 私人派对结算定时任务
						ServerfeastTask.runTask(data);
						message.reply(new JsonObject());
						break;
					case TimeTaskCmd.WORK_WORLD_BOSS_BATTLE:// 世界Boss定时任务
						WorldBossTask.runTask(data);
						message.reply(new JsonObject());
						break;
					case TimeTaskCmd.WORK_SERVER_SNATCH_OFFER:// 物资争夺悬赏结算定时任务
						ServerSnatchOfferTask.runTask(data);
						message.reply(new JsonObject());
						break;
					case TimeTaskCmd.WORK_CROSS_RANK_ACT_MATCH:
						RankActManager.matchCrossRankAct(data);
						break;
					case TimeTaskCmd.WORK_CROSS_RANK_ACT_TASK_REWARD:
						RankActManager.runCrossRankReward(data);
						break;
					case TimeTaskCmd.RANK_ACT_TASK_REWARD:
						RankActManager.sendRankReward(data);
						break;
				}
			} catch (Throwable e) {
				String errMsg = Tool.getException(e);
				logger.error("WorkVerticle error: " + errMsg);
				DBLogManager.addServerCrashLog(0, errMsg);
			}
		});

		consumer.completionHandler(res2 -> {
			if (res2.succeeded()) {
				logger.info("WorkVerticle handler registration has reached all nodes address:" + address);
				future.complete();
			} else {
				logger.error("WorkVerticle Registration failed! " + res2.cause().toString());
				future.fail(res2.cause());
			}
		});
	}


}
